<template>
  <a-drawer
    :title="title"
    :maskClosable="true"
    :width="drawerWidth"
    placement="right"
    :closable="true"
    @close="handleCancel"
    :visible="visible"
    style="height: calc(100% - 55px);overflow: auto;padding-bottom: 53px;">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="机构名称">
          <j-select-depart :disabled="status" v-decorator="['office', validatorRules.office]"/>
          <!--            <a-input placeholder="请输入机构名称" v-decorator="[ 'office', validatorRules.office]" />-->
        </a-form-item>

        <a-row :gutter="24">
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="信息化负责人">
              <a-input placeholder="负责人" :disabled="status" v-decorator="[ 'principal', validatorRules.principal]" />
            </a-form-item>
          </a-col>
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="联系电话">
              <a-input placeholder="联系电话" :disabled="status" v-decorator="[ 'principalPhone', validatorRules.principalPhone]" />
            </a-form-item>
          </a-col>
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="邮箱">
              <a-input placeholder="邮箱"  v-decorator="[ 'principalMail', validatorRules.principalMail]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="联系人">
              <a-input placeholder="联系人" :disabled="status" v-decorator="[ 'linkman', validatorRules.linkman]" />
            </a-form-item>
          </a-col>
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="联系电话">
              <a-input placeholder="联系电话" :disabled="status" v-decorator="[ 'linkmanPhone', validatorRules.linkmanPhone]" />
            </a-form-item>
          </a-col>
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="邮箱">
              <a-input placeholder="邮箱" :disabled="status" v-decorator="[ 'linkmanMail', validatorRules.linkmanMail]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-divider orientation="left">申请配置</a-divider>
        <a-row :gutter="24">
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="系统名称">
              <a-input placeholder="系统名称" :disabled="status" v-decorator="[ 'systemName', validatorRules.systemName]" />
            </a-form-item>
          </a-col>
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="主要用途">
              <a-input placeholder="主要用途":disabled="status"  v-decorator="[ 'mainUses', validatorRules.mainUses]" />
            </a-form-item>
          </a-col>
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="系统技术类型">
              <j-dict-select-tag :triggerChange="true" :disabled="status" placeholder="请选择技术类型" dictCode="sys_technology_type" v-decorator="[ 'sysTechnologyType', validatorRules.sysTechnologyType]"/>
            </a-form-item>
          </a-col>
        </a-row>
        <!--          <a-row :gutter="24">-->
        <!--            <a-form-item label="申请业务类型">-->
        <!--              <j-multi-select-tag-->
        <!--                dictCode="tos"-->
        <!--                type="checkbox"-->
        <!--                v-decorator="[ 'tos', validatorRules.tos]"-->
        <!--                :disabled="dis">-->
        <!--              </j-multi-select-tag>-->
        <!--            </a-form-item>-->
        <!--          </a-row>-->
<!--        <a-row :gutter="20">-->
<!--          <a-form-item label="申请配置"  :labelCol="labelCol"-->
<!--                       :wrapperCol="wrapperCol" >-->
<!--          </a-form-item>-->
<!--        </a-row>-->
        <a-row :gutter="24">
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="内网ip">
              <a-input ref="intranetIps"  :disabled="status" placeholder="多个Ip逗号分隔"  v-decorator="[ 'intranetIp', validatorRules.ip]" @change="ipTransform"/>
            </a-form-item>
          </a-col>
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="外网ip">
              <a-input ref="outernetIps"  :triggerChange="true"  autocomplete="off" :disabled="status" placeholder="多个Ip逗号分隔"  v-decorator="[ 'outernetIp', validatorRules.ip]" @change="ipTransform"/>
            </a-form-item>
          </a-col>
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="操作系统">
              <j-dict-select-tag :triggerChange="true" :disabled="status" placeholder="请选择操作系统" dictCode="os" v-decorator="[ 'os', validatorRules.os]"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24" v-show="issetmeal">
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="服务器">
              <j-dict-select-tag ref="meal" :triggerChange="true" :disabled="status"  placeholder="选择套餐" dictCode="jinan_server_expense,params,id,server_value &lt; '5'" v-decorator="[ 'setMeal', {rules: [{ required: true, message: '请选择服务器!' }]}]"  @change="mealChange"/>
<!--              <j-dict-select-tag ref="meal" :triggerChange="true" :disabled="status"  placeholder="选择套餐" dictCode="jinan_server_expense,params,id,server_value &lt; '5'" v-decorator="[ 'applyServer', validatorRules.applyServer]"  @change="mealChange"/>-->
            </a-form-item>
          </a-col>
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="数据库">
              <!--                <a-input placeholder="选择数据库"  v-decorator="[ 'serverNum', validatorRules.serverNum]" />-->
              <j-dict-select-tag ref="dataBase" :triggerChange="true" :disabled="status"  placeholder="选择数据库" dictCode="jinan_data_base,params,id" v-decorator="[ 'dataBase', validatorRules.dataBase]"  @change="dataBaseChange"/>
<!--              <j-dict-select-tag ref="dataBase" :triggerChange="true" :disabled="status"  placeholder="选择数据库" dictCode="jinan_data_base,params,id" v-decorator="[ 'applyDataBase', validatorRules.applyDataBase]"  @change="dataBaseChange"/>-->
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24" v-show="iscustom">
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="内存(G)">
              <a-input ref="memory" placeholder="内存" :disabled="status"  v-decorator="[ 'memory', validatorRules.memory]" @blur="billing"/>
<!--              <a-input ref="memory" placeholder="内存" :disabled="status"  v-decorator="[ 'applyMemory', validatorRules.applyMemory]" @blur="billing"/>-->
            </a-form-item>
          </a-col>
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="磁盘(G)">
              <a-input ref="disk" placeholder="磁盘"  :disabled="status" v-decorator="[ 'disk', validatorRules.disk]" @blur="billing" />
            </a-form-item>
          </a-col>
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="CPU">
              <j-dict-select-tag ref="cpu" :triggerChange="true" :disabled="status" placeholder="请选择CPU" dictCode="cpu" v-decorator="[ 'cpu', validatorRules.cpu]" @change="cpuChange"/>
<!--              <j-dict-select-tag ref="cpu" :triggerChange="true" :disabled="status" placeholder="请选择CPU" dictCode="cpu" v-decorator="[ 'applyCpu', validatorRules.applyCpu]" @change="cpuChange"/>-->
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="8">
              <a-form-item
                :labelCol="labelRow"
                :wrapperCol="wrapperRow"
                label="开通时间">
                <j-date ref="openTime" :disabled="status" v-decorator="[ 'openTime', validatorRules.openTime]" @change="dateChange"></j-date>
              </a-form-item>
            </a-col>
            <a-col :md="8">
              <a-form-item  :labelCol="labelRowCheckbox"
                            :wrapperCol="wrapperRowCheckbox" label="开放端口">
                <j-multi-select-tag
                  dictCode="ports"
                  type="checkbox"
                  v-decorator="[ 'openPorts', validatorRules.openPorts]"
                  :disabled="dis">
                </j-multi-select-tag>
              </a-form-item>
            </a-col>
            <a-col :md="8">
              <a-form-item
                :labelCol="labelRow"
                :wrapperCol="wrapperRow"
                label="服务器数量">
                <a-input-number ref="num" :min="1" :disabled="status" v-decorator="['serverNum',{'initialValue':1}]" @blur="billing"/>
              </a-form-item>
            </a-col>
        </a-row>
<!--        <div v-if="type=='1' || type=='2'">-->
<!--        <a-divider orientation="left">建议部署配置</a-divider>-->
<!--        <a-row :gutter="24" v-show="issetmeal">-->
<!--          <a-col :md="8">-->
<!--            <a-form-item-->
<!--              :labelCol="labelRow"-->
<!--              :wrapperCol="wrapperRow"-->
<!--              label="服务器">-->
<!--              <a-input ref="applyServer"  type="hidden" v-model='applyServer'/>-->
<!--              <j-dict-select-tag  :triggerChange="true" :disabled="status"  placeholder="选择套餐" dictCode="jinan_server_expense,params,id,server_value &lt; '5'" v-decorator="[ 'setMeal', validatorRules.setMeal]" @change="mealChange"/>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
<!--          <a-col :md="8">-->
<!--            <a-form-item-->
<!--              :labelCol="labelRow"-->
<!--              :wrapperCol="wrapperRow"-->
<!--              label="数据库">-->
<!--              <a-input ref="applyDatabase"  type="hidden" v-model='applyDatabase'/>-->
<!--              <j-dict-select-tag  :triggerChange="true" :disabled="status"  placeholder="选择数据库" dictCode="jinan_data_base,params,id" v-decorator="[ 'dataBase', validatorRules.dataBase]"  @change="dataBaseChange"/>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
<!--        </a-row>-->
<!--          <a-row :gutter="24" v-show="iscustom">-->
<!--          <a-col :md="8">-->
<!--            <a-form-item-->
<!--              :labelCol="labelRow"-->
<!--              :wrapperCol="wrapperRow"-->
<!--              label="内存(G)">-->
<!--              <a-input ref="applyMemory"  type="hidden" v-model='applyMemory'/>-->
<!--              <a-input  placeholder="内存" :disabled="status"  v-decorator="[ 'memory', validatorRules.memory]" @blur="billing"/>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
<!--          <a-col :md="8">-->
<!--            <a-form-item-->
<!--              :labelCol="labelRow"-->
<!--              :wrapperCol="wrapperRow"-->
<!--              label="磁盘(G)">-->
<!--              <a-input ref="applyDisk"  type="hidden" v-model='applyDisk'/>-->
<!--              <a-input  placeholder="磁盘"  :disabled="status" v-decorator="[ 'disk', validatorRules.disk]" @blur="billing"/>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
<!--          <a-col :md="8">-->
<!--            <a-form-item-->
<!--              :labelCol="labelRow"-->
<!--              :wrapperCol="wrapperRow"-->
<!--              label="CPU">-->
<!--              <a-input ref="applyCpu"  type="hidden" v-model='applyCpu'/>-->
<!--              <j-dict-select-tag  :triggerChange="true" :disabled="status" placeholder="请选择CPU" dictCode="cpu" v-decorator="[ 'cpu', validatorRules.cpu]" @change="cpuChange"/>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
<!--        </a-row>-->
<!--        </div>-->
        <a-row :gutter="24">
          <a-col :md="8">
            <a-form-item
              :labelCol="labelRow"
              :wrapperCol="wrapperRow"
              label="费用">
<!--              <a-input ref="cost" placeholder="费用" disabled="disabled"  v-decorator="[ 'cost', validatorRules.cost]" />-->
              <a-input ref="cost" placeholder="费用" disabled="disabled"  v-model="cost" />
            </a-form-item>
          </a-col>
        </a-row>
        <div v-if="type=='1' || type=='2'">
          <a-form-item
            label="审批意见"
            :labelCol="{lg: {span: 3}, sm: {span: 17}}"
            :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
            <a-textarea rows="4" placeholder="审批意见" :disabled="status" ref="remarks"
                        v-decorator="['remarks',validatorRules.remarks]" />
          </a-form-item>
        </div>
<!--          <a-col :md="8">-->
<!--            <div  v-show="expen">-->
<!--              <a-button type="primary"  @click="billing">计费</a-button>-->
<!--            </div>-->
<!--          </a-col>-->


      </a-form>
    </a-spin>
    <div class="drawer-bootom-button" v-show="!disableSubmit">
      <div  v-if="type=='0'||type=='1'" >
        <a-button key="back" @click="handleCancel">返回</a-button>
      </div>
      <div  v-else>
        <a-popconfirm title="确定放弃编辑？" @confirm="handleCancel" okText="确定" cancelText="取消">
          <a-button style="margin-right: .8rem">返回</a-button>
        </a-popconfirm>
        <a-popconfirm title="确定提交申请？" @confirm="handleSubmit" okText="确定" cancelText="取消">
          <a-button type="primary" :loading="confirmLoading">保存</a-button>
        </a-popconfirm>
      </div>
    </div>
  </a-drawer>
</template>

<script>
    import pick from 'lodash.pick'
    import {saveCloudList,editCloudList,annualPrice } from '@/api/api'
    import JMultiSelectTag from '@/components/dict/JMultiSelectTag'
    import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
    import JDate from '@/components/jeecg/JDate'
    import {ajaxFilterDictText} from '@/components/dict/JDictSelectUtil'
    import {getAnnualPrice,getServerExpense1,getDataBaseName,getServerParam,myDate} from '@/utils/ipDate'
    export default {
        components: {
            JMultiSelectTag,
            JSelectDepart,
            JDate,

        },
        name: "cloudApplyListModal",
        data(){
            return{
                cost:'',
                form: this.$form.createForm(this),
                title:"操作",
                visible: false,
                status:false,
                type:'',
                expen:true,
                iscustom:true,
                issetmeal:true,
                sumbit:false,
                model: {},
                labelCol: {
                    xs: { span: 24 },
                    sm: { span: 2 },
                },
                wrapperCol: {
                    xs: { span: 24 },
                    sm: { span: 16 },
                },
                labelRow: {
                    xs: { span: 12 },
                    sm: { span: 10 },
                },
                wrapperRow: {
                    xs: { span: 12 },
                    sm: { span: 14 },
                },
              labelRowCheckbox: {
                xs: { span: 8 },
                sm: { span: 10 },
              },
              wrapperRowCheckbox: {
                xs: { span: 10 },
                sm: { span: 14 },
              },
                dis:false,
                hiding:true,
                drawerWidth:1000,
                confirmLoading: false,
                disableSubmit:false,
                validatorRules:{
                    principalPhone:{rules: [{validator: this.validatePhone}]},
                    linkmanPhone:{rules: [{validator: this.validatePhone}]},
                    principalMail:{rules: [{validator: this.validateEmail}]},
                    linkmanMail:{rules: [{validator: this.validateEmail}]},
                    memory:{rules: [{validator: this.validateNum}]},
                    disk:{rules: [{validator: this.validateNum}]},
                    ip:{rules: [{validator: this.ipVerify}]}
                },
            }
        },
        methods:{
          ipTransform(e){
            var val = e.currentTarget
            if((val.value).indexOf("，",",")>-1){
              val.value = (val.value).replace("，",",");
            }
            this.billing();
          },
          numChange(e){
            let num = e;
            this.cost = this.$refs.cost.$refs.input.value * e;
          },
          mealChange(e){
            this.billing("1",e);
          },
          dataBaseChange(e){
            this.billing("2",e);
          },
          async cpuChange(e){
            let cpuValue = await ajaxFilterDictText("cpu",e);
            this.billing("3",cpuValue);
          },
          dateChange(e){
            this.billing("4",e);
          },
          async billing(type,e){
            let date = type=="4"?e:this.$refs.openTime.value==undefined?new Date().format("yyyy-MM-dd"):this.$refs.openTime.value;
            let sum = 0;
            let ipsValue = this.$refs.outernetIps.value;
            let dataBaseVal = type=="2"?e:this.$refs.dataBase.value;
            let mealId = type=="1"?e:this.$refs.meal.value;
            let num = this.$refs.num.value;
            // let type = this.$refs.isType.value;
            if(ipsValue!=undefined && ipsValue != '' && ipsValue != null){//ip费用
              sum = parseFloat((sum + await getAnnualPrice(ipsValue.split(",").length,date)).toFixed(2));
            }
            // if(type=="0"){//服务器选择
            if(mealId!=undefined && mealId != '' && mealId != null){
              sum = parseFloat((sum + await getServerExpense1(mealId,date)).toFixed(2));
            }
            // }else if(type=="1"){//自定义选择
            //cpu、内存、硬盘计算费用
            var re1 = /(\d{1,3})+(?:\.\d+)?/g
            let cpu = parseInt(type=="3"?e.match(re1):this.$refs.cpu.$el.innerText.match(re1));
            let disk = parseInt(this.$refs.disk.value);
            let memory = parseInt(this.$refs.memory.value);
            if(cpu ==NaN && disk==NaN &&memory==NaN){
              sum=sum;
            }else {
              sum = parseFloat((sum + await getServerParam(cpu,disk,memory,date)).toFixed(2));
            }
            // }
            if(dataBaseVal != undefined && dataBaseVal != '' && dataBaseVal != null){//数据库费用
              sum = parseFloat((sum + await getDataBaseName(dataBaseVal,date)).toFixed(2));
            }
            this.$refs.cost.$refs.input.value = sum*num;
            this.cost=sum*num;
            // this.sumbit = true;
          },
          ipVerify(rule, value, callback){
            var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
            if(!value){
              callback()
            }else{
              if(value.indexOf(",")>-1){
                value = value.replace("，",",");
                let val = value.split(",");
                let sign = 1;
                for(let i=0;i<val.length;i++){
                  if(!reg.test(val[i])){
                    sign++;
                    callback("IP地址不规范!")
                    break;
                  }
                }
                if(sign == 1){
                  callback()
                }
              }else{
                if(!reg.test(value)){
                  callback("IP地址不规范!")
                }else{
                  callback()
                }
              }
            }
          },
            validateNum(rule, value, callback){
                if(!value){
                    callback()
                }else{
                    if(new RegExp(/[^\d]/g).test(value)){
                        callback("请输入正确的数字!")
                    }else{
                        callback()
                    }
                }
            },
            validateEmail(rule, value, callback){
                if(!value){
                    callback()
                }else{
                    if(new RegExp(/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/).test(value)){
                        callback()
                    }else{
                        callback("请输入正确格式的邮箱!")
                    }
                }
            },
            validatePhone(rule, value, callback){
                if(!value){
                    callback()
                }else{
                    if(new RegExp(/^1[3|4|5|7|8][0-9]\d{8}$/).test(value)){
                        callback()
                    }else{
                        callback("请输入正确格式的手机号码!");
                    }
                }
            },
            close () {
                this.$emit('close');
                this.visible = false;
                this.disableSubmit = false;
            },
            add () {
                this.edit({type:'4'});
            },
            edit(record){
                 this.cost=record.cost;
                if(record.type=="4"){
                  this.status=false;
                  this.expen=true;
                  this.type='4';
                }else if(record.type=='2'){
                  this.status=false;
                  this.expen=true;
                  this.type=record.type;
                }else{
                  this.status=true;
                  this.expen=false;
                  this.type=record.type;
                }
                this.form.resetFields();
                this.model = Object.assign({}, record);
                this.visible = true;
                this.$nextTick(() => {
                  this.form.setFieldsValue(pick(this.model,'office', 'principal','principalPhone','principalMail','linkman','linkmanPhone'
                    ,'linkmanMail','systemName','mainUses','intranetIp','outernetIp',/*'tos',*/'serverNum','dataBase','sysTechnologyType',
                    'os','memory','disk','cpu','openPorts','createTime','setMeal','openTime','lastSettlementTime','cost','remarks','applyServer','applyMemory','applyCpu','applyDataBase','applyDisk'))
                });
            },
            handleCancel () {
                this.close()
            },
            handleSubmit () {
                const that = this;
                let type={type:"0"};
                var price = this.$refs.cost.$refs.input.value;
                // if(this.sumbit){
                    // 触发表单验证
                    this.form.validateFields((err, values) => {
                        if (!err) {
                            that.confirmLoading = true;
                            let formData = Object.assign(this.model, values,type);
                            formData.cost = price;
                            let obj;
                            // this.eitdData(formData);
                            if(!this.model.id){
                                obj=saveCloudList(formData);
                            }else{
                                obj=editCloudList(formData);
                            }
                            obj.then((res)=>{
                                if(res.success){
                                    that.$message.success(res.message);
                                    that.$emit('ok');
                                }else{
                                    that.$message.warning(res.message);
                                }
                            }).finally(() => {
                                that.confirmLoading = false;

                                that.close();
                            })

                        }
                    })
                // }else{
                //     that.$message.warning("请重新计费后提交");
                // }
            },
        }
    }
    Date.prototype.format = function(fmt) {
      var o = {
        "M+" : this.getMonth()+1,                 //月份
        "d+" : this.getDate(),                    //日
        "h+" : this.getHours(),                   //小时
        "m+" : this.getMinutes(),                 //分
        "s+" : this.getSeconds(),                 //秒
        "q+" : Math.floor((this.getMonth()+3)/3), //季度
        "S"  : this.getMilliseconds()             //毫秒
      };
      if(/(y+)/.test(fmt)) {
        fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
      }
      for(var k in o) {
        if(new RegExp("("+ k +")").test(fmt)){
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
        }
      }
      return fmt;
    }
</script>

<style scoped>

</style>